package Action.Manager;

import Action.Sys.Setting;
import Bean.BookCommentEntity;
import Bean.LoanBookLogRecord;
import Bean.Log.HistoricalData;
import Bean.Log.OrderLog;
import Bean.Log.SystemLogEntity;
import Bean.Log.UserLogEntity;
import Bean.UserinfoEntity;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.hibernate.Session;
import tools.HibernateTools;

import java.util.List;

public class UserInfoManage extends ActionSupport {
    List<UserinfoEntity> userinfos;
    String key="";
    int modify_id;
    String flag;
    UserinfoEntity userinfoEntity;

    public String show() throws Exception {
        clearActionErrors();
        Session session= HibernateTools.getSession();
        userinfos=session.createQuery("from UserinfoEntity ORDER BY id").getResultList();
        if (userinfos.size()==0)
        {
            addActionError("没有用户信息");
            return INPUT;
        }
        //取消过于详细的日志记录
//        SystemLogEntity.addLog((Integer) ActionContext.getContext().getSession().get("adminid"), this, Setting.SystemLog_flag_ManagerUserData);

        return SUCCESS;
    }
    public String find() throws Exception {
        clearActionErrors();
        if (key.equals(""))
            return show();
        Session session= HibernateTools.getSession();
        //尝试获得id
//        int id_num=-1;
//        try{
//            id_num=Integer.valueOf(key);
//        }catch (Exception e){
//            //防止转换失败
//            id_num=-1;
//        }
        userinfos=session.createQuery("from UserinfoEntity  where name  like ? or username like ? or cast( id as string )like ? " +
                "or cast(phone as string ) like ?")
                .setParameter(0,"%"+key+"%")
                .setParameter(1, "%"+key+"%")
                .setParameter(2, "%"+key+"%")
                .setParameter(3, "%"+key+"%")
                .getResultList();
//        userinfos=session.createQuery("from UserinfoEntity  where name  = ?").setParameter(0, key).getResultList();
        if (userinfos.size()==0)
        {
            addActionError("没有用户信息");
            return INPUT;
        }
        SystemLogEntity.addLog((Integer) ActionContext.getContext().getSession().get("adminid"), this, Setting.SystemLog_flag_ManagerUserData);
        return SUCCESS;
    }
    public String modify() throws Exception {
        clearActionErrors();
        userinfoEntity=getUserInfo(modify_id);
        Session session=HibernateTools.getSession();
        session.saveOrUpdate(userinfoEntity);

        SystemLogEntity.addLog((Integer) ActionContext.getContext().getSession().get("adminid"), this, Setting.SystemLog_flag_AltUserData);
        HibernateTools.commit(session);
        return SUCCESS;
    }
public String del() throws Exception {
        clearActionErrors();
        userinfoEntity=getUserInfo(modify_id);
        Session session=HibernateTools.getSession();
        //应该检查用户是否有没有完成的订单--如果有应该阻止
        //删除用户订单和订单日志
        List<LoanBookLogRecord> loanBookLogRecords=session.createQuery("from LoanBookLogRecord where userId="+userinfoEntity.getId())
                .getResultList();
    for (LoanBookLogRecord loanBookLogRecord : loanBookLogRecords) {
        //订单检查
        if (loanBookLogRecord.getState().equals(Setting.LoanBook_state_reservation)||loanBookLogRecord.getState().equals(Setting.LoanBook_state_need_Return)
        ||loanBookLogRecord.getState().equals(Setting.LoanBook_state_need_TimeOut)){
            //存在没有完成的订单
            addActionError("本用户存在没有完成的订单,不要允许执行删除");
            HibernateTools.commit(session);
            return ERROR;
        }
    }
        for (LoanBookLogRecord loanBookLogRecord : loanBookLogRecords) {
            List<OrderLog> orderLogs=session.createQuery("from OrderLog where orderid="+loanBookLogRecord.getId())
                    .getResultList();
            for (OrderLog orderLog : orderLogs) {
                session.remove(orderLog);
            }
            session.remove(loanBookLogRecord);
        }
        //删除用户日志
        List<UserLogEntity> userLogEntities=session.createQuery("from UserLogEntity where userId="+userinfoEntity.getId())
                .getResultList();
    for (UserLogEntity userLogEntity : userLogEntities) {
        session.remove(userLogEntity);
    }

    //用户评论----可以不删除将按照"已删除用户原id为XX"的形式显示---这里选择删除
    List<BookCommentEntity> bookCommentEntities=session.createQuery("from BookCommentEntity where userId="+userinfoEntity.getId())
            .getResultList();
    for (BookCommentEntity bookCommentEntity : bookCommentEntities) {
        session.remove(bookCommentEntity);
    }
    session.delete(userinfoEntity);

    //修改今天的系统统计
    HistoricalData historicalData=session.get(HistoricalData.class, tools.TimeTools.formatTime(0));
    if (historicalData==null){
        historicalData=new HistoricalData();
        historicalData.setTimestamp(tools.TimeTools.formatTime(0));
    }
    historicalData.setNewUserNum(historicalData.getNewUserNum()-1);
    session.saveOrUpdate(historicalData);


    SystemLogEntity.addLog((Integer) ActionContext.getContext().getSession().get("adminid"), this, Setting.SystemLog_flag_DelUser);
    HibernateTools.commit(session);
    addActionMessage("删除成功");
    return SUCCESS;
    }

    private UserinfoEntity getUserInfo(int id) {
        Session session=HibernateTools.getSession();
        return session.get(UserinfoEntity.class, id);
    }


    public List<UserinfoEntity> getUserinfos() {
        return userinfos;
    }

    public void setUserinfos(List<UserinfoEntity> userinfos) {
        this.userinfos = userinfos;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public int getModify_id() {
        return modify_id;
    }

    public void setModify_id(int modify_id) {
        this.modify_id = modify_id;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public UserinfoEntity getUserinfoEntity() {
        return userinfoEntity;
    }

    public void setUserinfoEntity(UserinfoEntity userinfoEntity) {
        this.userinfoEntity = userinfoEntity;
    }


}
